package dr.joketalker.model;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.net.ftp.FTP;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Environment;
import android.util.Log;
import dr.joketalker.account.AccountManager;
import dr.joketalker.dao.FactoryDAO;
import dr.joketalker.dao.JokeDAO;
import dr.joketalker.entity.Joke;
import dr.joketalker.entity.User;

public class ProfilModel extends MyModel implements OnCompletionListener, OnInfoListener{

	protected MediaRecorder mRecorder = null;
	protected MediaPlayer   mPlayer = null;
	
	protected String directoryPath;
	protected String savePath;
	protected String fileName;
	
	
	protected boolean mRecording = false;
	
	protected MyFtpClient myFtpClient;
	
	final static String EXTENSION = ".3gp";
	
	protected JokeDAO jokeDao = FactoryDAO.getJokeDao();
	//Stopwatch timer = new Stopwatch();
	
	public ProfilModel(){
		mPlayer = new MediaPlayer();
		mRecorder = new MediaRecorder();
		mRecorder.setOnInfoListener(this);
		
		directoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/JokeTalker";
      
	      File file = new File(directoryPath);
	      if(!file.isDirectory()){
	    	  file.mkdir();
	      }
	      mPlayer.setOnCompletionListener(this);
	}
	
	public void uploadFtp(Joke joke){
		try{
			String uploadPath = MyFtpClient.JOKEDIRECTORY + File.separator + joke.getLanguage() +File.separator + joke.getCategory();
			String fileName = joke.getId()+EXTENSION;
			
			
			myFtpClient = MyFtpClient.getInstance();
			
			myFtpClient.connect();
			myFtpClient.login();
					
			boolean isDirectory = myFtpClient.changeWorkingDirectory(uploadPath);
			if(!isDirectory){
				myFtpClient.makeDirectory(uploadPath);
			}
						
			myFtpClient.setFileType(FTP.BINARY_FILE_TYPE);
			myFtpClient.enterLocalPassiveMode();
			
			BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream(new File(savePath)));
			
			boolean result = myFtpClient.storeFile(fileName,buffIn);// return true if successful
			buffIn.close();
		
			}catch(Exception ex){
				myDebug.v(ex.toString());
			}
	}
	
	public void insertDb(Joke joke){
		
		User user = AccountManager.getInstance().getLoggedUser();
		joke.setUser(user);
		
		long id = jokeDao.create(joke);
		myDebug.v("created in db with id: "+id);
		
		joke.setId(id);
		uploadFtp(joke);
	}
	
	
	
		
	public void startRecording(String newFileName) {
		
		//mRecorder.setMaxDuration(1000 * 60 * 3);
		savePath = directoryPath + File.separator + newFileName + EXTENSION;
		fileName = newFileName+EXTENSION;
		
		File file = new File(savePath);

		int i = 0;
		while(file.exists()){
		
			savePath = directoryPath + File.separator + newFileName +i+ EXTENSION;
			file = new File(savePath);
			i++;
			
			fileName = newFileName+EXTENSION;
		}
		
        
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(savePath);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e("my", "prepare() failed");
            Log.e("my", e.toString());
        }

        mRecorder.start();
        mRecording = true;
        notifyObservers();
        

    }
    
    public void startPlaying() {
        
        try {
            mPlayer.setDataSource(savePath);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.e("my", "prepare() failed");
        }
        
        mRecording = false;
    }
    
    public void stop() {    	  	
    	if(mRecording){
    		mRecorder.stop();
    		mRecorder.release();
    		mRecorder = null;
    	}else{
    		mPlayer.stop();
    	}
        mRecording = false;
        notifyObservers();
    }

	@Override
	public void onCompletion(MediaPlayer e) {
		  notifyObservers();
	}

	@Override
	public void onInfo(MediaRecorder arg0, int arg1, int arg2) {
		myDebug.v("vrm onInfo");
		notifyObservers();
		
	}
	
	public MediaPlayer getMediaPlayer(){
		return mPlayer;
	}
	public MediaRecorder getMediaRecorder(){
		return mRecorder;
	}
	public boolean isRecording(){
		return mRecording;
	}
	
}
